package com.l2jfrozen.gameserver.model.dps;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;

import java.util.logging.Logger;
import com.l2jfrozen.Config;
import com.l2jfrozen.gameserver.model.actor.instance.L2PcInstance;
import com.l2jfrozen.gameserver.network.L2GameClient;
import com.l2jfrozen.gameserver.network.L2GameClient.GameClientState;
import com.l2jfrozen.gameserver.thread.LoginServerThread;
import com.l2jfrozen.util.ResourceUtil;
import com.l2jfrozen.util.database.L2DatabaseFactory;
import com.l2jfrozen.util.random.Rnd;

public class FakePlayers
{
	private static Logger _log = Logger.getLogger(FakePlayers.class.getName());
	
	private static final String CLEAR_OFFLINE_TABLE = "DELETE FROM fake_players";
	private static final String LOAD_OFFLINE_STATUS = "SELECT * FROM fake_players";

	private static FakePlayers _instance;
	
	public static FakePlayers getInstance()
	{
		if(_instance == null)
		{
			_instance = new FakePlayers();
		}
		return _instance;
	}
	
	private FakePlayers()
	{
		storeFakePlayers();
	}

	public static void storeFakePlayers()
	{
		_log.info("FakePlayers: Activated.");
		Connection con = null;
		int nPlayers = 0;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement stm = con.prepareStatement(LOAD_OFFLINE_STATUS);
			ResultSet rs = stm.executeQuery();

			while(rs.next())
			{
				L2PcInstance player = null;
				
				try
				{
					L2GameClient client = new L2GameClient(null);
					player = L2PcInstance.load(rs.getInt("charId"));
					
					client.setActiveChar(player);
					client.setAccountName(player.getAccountName());
					client.setState(GameClientState.IN_GAME);
					
					player.setClient(client);
					player.isFakePlayer();
					player.spawnMe(player.getX(), player.getY(), player.getZ());
					
					//LoginServerThread.getInstance().addGameServerLogin(player.getAccountName(), client);
					
					if(Config.FAKE_PLAYERS_SIT)
					{
						int _random = Rnd.get(100);
						
						if (_random <= 50)
						{
							player.sitDown();
						}
					}
					//player.setOnlineStatus(true);
					//player.restoreEffects();
					player.broadcastUserInfo();
					nPlayers++;
				}
				catch(Exception e)
				{
					_log.info("Fake Players Engine: Error loading player: " + player); //, e);
					
					if(player != null)
					{
						player.deleteMe();
					}
				}
			}
			rs.close();
			stm.close();
			_log.info("Loaded: " + nPlayers + " Fake Players.");
		}
		catch(Exception e)
		{
			_log.info("Fake Players Engine : Error while loading player: "); //, e);
		}
		finally
		{
			ResourceUtil.closeConnection(con);
		}
	}
}